package com.example.springboot_code_read.propertiesResource;

import org.springframework.core.env.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.support.ResourcePropertySource;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesResourceTest {

    public static void main(String[] args) throws IOException {

        Properties propertyResource = PropertiesLoaderUtils.loadProperties(new ClassPathResource("application.properties"));
        PropertySource propertiesPropertySource = new PropertiesPropertySource("properties", propertyResource);

        ClassPathResource classPathResource = new ClassPathResource("application.properties");
        PropertySource resourcePropertySource = new ResourcePropertySource("resource", classPathResource);

        Map<String, Object> map = new HashMap<>();
        map.put("app.name", "Spring-Reading");
        map.put("app.version", "1.0.0");
        PropertySource mapPropertySource = new MapPropertySource("mapSource", map);

        // 访问系统环境变量
        Map mapEnv = System.getenv();
        PropertySource envPropertySource = new SystemEnvironmentPropertySource("systemEnv", mapEnv);

        // 解析命令行参数
        String[] myArgs = {"--appName=MyApplication", "--port=8080"};
        PropertySource commandLinePropertySource = new SimpleCommandLinePropertySource(myArgs);

        CompositePropertySource compositePropertySource = new CompositePropertySource("composite");
        compositePropertySource.addPropertySource(propertiesPropertySource);
        compositePropertySource.addPropertySource(resourcePropertySource);
        compositePropertySource.addPropertySource(mapPropertySource);
        compositePropertySource.addPropertySource(envPropertySource);
        compositePropertySource.addPropertySource(commandLinePropertySource);

        for (PropertySource re : compositePropertySource.getPropertySources()) {
            System.out.printf("Name: %-15s || Source: %s%n", re.getName(), re.getSource());
        }

    }

}
